package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Controller
public class PhoneLoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserMapper userMapper;

    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/loginPage.do")
    public String loginPage(){

        return "login";
    }



    /**
     * 登录页面
     * @return
     */
    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response){

        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());

            return "login";
        }
        // 手机号是否存在
        User userFromDB = userMapper.selectUserByPhone(loginUser.getPhone());

        if (userFromDB == null){
            model.addAttribute("error","手机号不存在");
            return "login";
        }
        // 密码校验
        String loginUserPassword = loginUser.getPassword();

        String salt = userFromDB.getSalt();

        String fromDBPassword = userFromDB.getPassword();

        String md5String = Md5Utils.getMD5String(loginUserPassword + salt);
        if (!md5String.equals(fromDBPassword)){
            model.addAttribute("error","密码错误");
            return "login";
        }
        // 加密用户
        TokenUtils.responseTokenByCookie(userFromDB,response);
        // 把用户信息放入Redis， 设置过期时间为 cookie的过期时间（30 min）
        redisTemplate.opsForValue().set("user", JSON.toJSONString(userFromDB),30, TimeUnit.MINUTES);

        return "redirect:list.do";
    }
}
